I want to load an image from url and draw it on my canvas. My canvas takes full window size and I only want the image to be shown on the mouse position with a size of 100x100. Below is my code:
drawImage(imageUrl) {
const ctx = this.canvas.getContext('2d');
ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
const image = new Image();
image.onload = () => {
ctx.imageSmoothingEnabled = false;
ctx.drawImage(image, this.state.mousePos.x, this.state.mousePos.y,
100, 100);
};
image.src = 'https://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png';
}
the image can be drawn on the web page but the quality is pretty low. Below is the orianl image from above link:
below is the image is shown on my canvas:
You can compare two images and their quality is quite different. How can I draw a high quality of the image on canvas?
Once we have a reference to our source image object we can use the drawImage() method to render it to the canvas. As we will see later the drawImage() method is overloaded and has several variants. In its most basic form it looks like this: drawImage(image, x, y)
The drawImage() method draws an image, canvas, or video onto the canvas. The drawImage() method can also draw parts of an image, and/or increase/reduce the image size. Note: You cannot call the drawImage() method before the image has loaded.
The default type is image/png ; this image format will be also used if the specified type is not supported.
let canvas = document.getElementById('c'),ctx = canvas.getContext('2d');
const image = new Image();
image.onload = () => {
ctx.imageSmoothingEnabled = false;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(image, 50, 50,500,500);
};
image.src = 'https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.svg?v=6e4af45f4d66';
canvas{
border : 2px solid black;
}
<canvas id='c' width=500 height=500/>
Use svg if you relay on image quality.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With