HTML5中的SVG canvas元素 [英] SVG in HTML5 canvas element

查看:125
本文介绍了HTML5中的SVG canvas元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在HTML5画布元素中包含SVG图像,以便在更改浏览器窗口大小时调整SVG的大小?

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?

推荐答案

这需要一些样板代码来证明,所以我只是指出你正确的方向。

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

说你有访问名为 myCanvas 的画布对象/元素。执行 var ctx = myCanvas.getContext('2d')时, ctx 是<$ c $的实例C> CanvasRenderingContext2D 。现在,当您绘制图像 img 时,执行 ctx.drawImage(img,dx,dy,sw,sh)其中:

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 dy 是左上角的偏移量。

  • sw sh 是图像的绝对大小。

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

因此,您使用 sw 和 sh 。您希望它们依赖于您可以使用 myCanvas.height myCanvas.width 访问的画布大小。

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.

您希望画布宽度/高度取决于窗口大小。使用 window.innerWidth window.innerHeight 访问窗口大小。调整大小时,您可以像这样监听此事件: window.addEventListener('resize',function(evt){/ * handle resize here * /}); 。示例:

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
};

这篇关于HTML5中的SVG canvas元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆