Örnek
Şöyle yaparız
Kullanmak için şöyle yaparız<canvas id="canvas" width="300" height="300"></canvas>
let canvas = document.getElementById('canvas'); let ctx = canvas.getContext('2d'); // Create our image let newImage = new Image(); newImage.src = 'https://fjolt.com/images/misc/202203281.png' // When it loads newImage.onload = () => { // Draw the image onto the context ctx.drawImage(newImage, 0, 0, 250, 208); }Açıklaması şöyle
When the image loads (newImage.onload), then we draw the image onto our canvas. To do that, we use ctx.drawImage(). The syntax is shown below.
ctx.drawImage(image, x, y, width, height)
If declared like this, ctx.drawImage() only has 5 arguments:
- image - the image we want to use, is generated from our new Image() constructor.
- x - the x position on the canvas for the top left corner of the image.
- y - the y position on the canvas for the top left corner of the image.
- width - the width of the image. If left blank, the original image width is used.
- height - the height of the image. If left blank, the original image height is used.
toDataURL metodu
İmzası şöyle
toDataURL(type, encoderOptions) has two arguments which lets us change the way the canvas is encoded. This lets us save files as other formats, such as jpg.
Those two arguments can be defined as follows:
- type, which is a filetype, in the format image/png.
- encoderOptions, which is a number between 0 and 1, defining the image quality. This is only supported by file formats that have lossy compression, like webp or jpg.
Örnek
Şöyle yaparız
// Convert our canvas to a data URL let canvasUrl = canvas.toDataURL("image/jpeg", 0.5); console.log(canvasUrl); // Outputs // "data:image/jpeg;base64,/9j/...Örnek
Şöyle yaparız
let canvas = document.getElementById('canvas'); let ctx = canvas.getContext('2d'); // Canvas code goes here // ... document.getElementById('download').addEventListener('click', function(e) { // Convert our canvas to a data URL let canvasUrl = canvas.toDataURL(); // Create an anchor, and set the href value to our data URL const createEl = document.createElement('a'); createEl.href = canvasUrl; // This is the name of our downloaded file createEl.download = "download-this-canvas"; // Click the download button, causing a download, and then remove it createEl.click(); createEl.remove(); });