SVG in HTML5 canvas element

2019-06-10 15:50发布

How can I include a SVG image in a HTML5 canvas element, so that it also adjusts the size of the SVG when you change the size of the browser window?

1条回答
劳资没心,怎么记你
2楼-- · 2019-06-10 16:03

This requires quite some boilerplate code to demonstrate so I'm just gonna point you in the right direction.

Say you have access to a canvas object/element named myCanvas. When you execute var ctx = myCanvas.getContext('2d') then ctx is an instance of CanvasRenderingContext2D. Now when you draw your image img you execute ctx.drawImage(img, dx, dy, sw, sh) where:

  • dx and dy is the offset from the top-left corner.
  • sw and sh is the absoulte size of the image.

So, you adjust the image size with sw and sh. You want them to depend on the canvas size which you can access with myCanvas.height and myCanvas.width.

You want the canvas width/height to depend on window size. Window size is accessed with window.innerWidth and window.innerHeight. When you resize you can listen to this event like this: window.addEventListener('resize', function (evt) { /* handle resize here */ });. Example:

var updateCanvasSize, canvasRelativeSize;

canvasRelativeSize = .5;

updateCanvasSize = function (evt) {
  myCanvas.width  = canvasRelativeSize * window.innerWidth;
  myCanvas.height = canvasRelativeSize * window.innerHeight;
  draw(); // redraws the canvas since size has changed
};
查看更多
登录 后发表回答