0

我创建了一个使用 HTML5 Canvas 元素的基于 HTML5 的绘图应用程序。我已经编写了在 Canvas 上绘制草图的代码。

在此处输入图像描述

画布的原始尺寸为 500 px x 500 px 。所有的图纸都是根据这个制作的。现在我的问题是我需要将 Canvas 大小更改为 1000 x 1000 并希望使图纸覆盖整个新画布。有什么简单的方法可以做到这一点,而不是直接修改像素位置?

4

2 回答 2

3

您可以使用 CSS 更改画布大小并保持画布元素的宽度和高度属性不变。这将创建您需要的拉伸。

于 2013-04-05T00:14:58.813 回答
0

我相信您想要做的是缩放并可能转换画布的位置。

这是一个工作示例:http ://marketimpacts.com/storage/9781118385357%20ls0701%20Resizing%20and%20Scaling%20the%20Canvas.htm

如果这不是您需要的,其他 Canvas 示例在这里: http ://donkcowan.com/html5-canvas-for-dummies/

这是代码:

<!DOCTYPE HTML> <html> <head> <script> 

// SUMMARY: Draws random circles on a 
// resized and rescaled canvas.

// A. WINDOW LOAD function.                      
window.onload = function()
{ 
   // A1. CANVAS definition standard variables.            
   canvas  = document.getElementById("canvasArea"); 
   context = canvas.getContext("2d");

   // A2. PARAMETERS for circles.
   var numCircles = 300;
   var maxRadius  = 20;
   var minRadius  = 3;
   var colors     = ["aqua",  "black", "blue",  "fuchsia",
                     "green", "cyan",  "lime",  "maroon",
                     "navy",  "olive", "purple","red",
                     "silver","teal",  "yellow","azure",
                     "gold",  "bisque","pink",  "orange"];
   var numColors  =  colors.length;

   // A3. RESIZE & RESCALE canvas.
   canvas.width  = 400;   canvas.height = 100;
   context.scale(.7, .3);

   // A4. CREATE circles.
   for(var n=0; n<numCircles; n++)
   {
      // A5. RANDOM values for circle characteristics.
      var xPos       =  Math.random()*canvas.width;
      var yPos       =  Math.random()*canvas.height;
      var radius     =  minRadius+(Math.random()*(maxRadius-minRadius));
      var colorIndex =  Math.random()*(numColors-1);
      colorIndex     =  Math.round(colorIndex);
      var color      =  colors[colorIndex];

      // A6. DRAW circle.
      drawCircle(context, xPos, yPos, radius, color);
   }
};
// B. CIRCLE drawing function.
function drawCircle(context, xPos, yPos, radius, color)
{
   //B1. PARAMETERS for shadow and angles.
   var startAngle        = (Math.PI/180)*0;
   var endAngle          = (Math.PI/180)*360;
   context.shadowColor   = "gray";
   context.shadowOffsetX = 1;
   context.shadowOffsetY = 1;
   context.shadowBlur    = 5;

   //B2. DRAW CIRCLE
   context.beginPath();
   context.arc(xPos, yPos, radius, startAngle, endAngle, false);
   context.fillStyle = color;
   context.fill();              

}
</script> </head> <body> 
<!-- C. CANVAS definition -->
<div    style = "width:200px;   height:200px; 
                 margin:0 auto; padding:5px;">
<canvas id    = "canvasArea" 
        width = "200"  height = "200" 
        style = "border:2px solid black">
Your browser doesn't currently support HTML5 Canvas.
</canvas> </div> 
</body> </html>
于 2013-04-05T20:08:55.230 回答