Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw image from URL on canvas with original quality

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:

enter image description here

below is the image is shown on my canvas:

enter image description here

You can compare two images and their quality is quite different. How can I draw a high quality of the image on canvas?

like image 661
Joey Yi Zhao Avatar asked Oct 26 '17 06:10

Joey Yi Zhao


People also ask

How do I render an image in 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)

Which method is used to draw an image on a canvas?

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.

What is the default image content of the canvas?

The default type is image/png ; this image format will be also used if the specified type is not supported.


1 Answers

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.

like image 83
Durga Avatar answered Sep 28 '22 04:09

Durga