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:
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
anddy
is the offset from the top-left corner.sw
andsh
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
};