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?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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 executevar ctx = myCanvas.getContext('2d')thenctxis an instance ofCanvasRenderingContext2D. Now when you draw your imageimgyou executectx.drawImage(img, dx, dy, sw, sh)where:dxanddyis the offset from the top-left corner.swandshis the absoulte size of the image.So, you adjust the image size with
swandsh. You want them to depend on the canvas size which you can access withmyCanvas.heightandmyCanvas.width.You want the canvas width/height to depend on window size. Window size is accessed with
window.innerWidthandwindow.innerHeight. When you resize you can listen to this event like this:window.addEventListener('resize', function (evt) { /* handle resize here */ });. Example: