javascript - 缩放 HTML Canvas 元素

标签 javascript html canvas scale

在我的主要项目中,我有很多小 Canvas 元素(想想: Sprite map 中的 Sprite ),我需要能够在将它们绘制到主 Canvas 之前缩放它们。这是我的基本代码:

var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;

var miniCanvas = document.createElement('canvas');
var miniCanvasContext = miniCanvas.getContext('2d');

miniCanvasContext.beginPath();
miniCanvasContext.rect(0,0,100,100);
miniCanvasContext.closePath();
miniCanvasContext.fillStyle = 'red';
miniCanvasContext.fill();

miniCanvasContext.scale(2,2);//THIS IS THE PROBLEM


ctx.drawImage(miniCanvas, 100, 100);

此测试在 jsfiddle 上进行:JSFIDDLE

本质上,我需要将这个红色方 block 的大小增加两倍。

谢谢。

最佳答案

drawImage 方法有一个版本,可以让您通过缩放绘制 miniCanvas:

// the last 2 parameters are scaled Width & scaled Height

// parameters:
// 1st: the image source
// 2nd,3rd: the upper-left part of the source to clip from
// 4th,5th: the width & height to clip from the source
// 6th,7th: the upper-left part of the canvas to draw the clipped image
// 8th,9th: the scaled width & height to draw on the canvas

ctx.drawImage(miniCanvas, 0,0,100,100, 0,0,200, 200);

关于javascript - 缩放 HTML Canvas 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25717157/

相关文章:

javascript - 为什么在比较字符串时使用 === 而不是 ==

javascript - Jquery中如何通过索引获取子元素?

javascript - 更改输入标记

canvas - Three.js 和 HTML5 Canvas toDataURL

javascript - 当 Canvas 全屏时,如何获取 HTML5 Canvas 上的鼠标位置?

javascript - 如何在JavaScript中传输 'devicemotion'属性?

javascript - 使用 extend.js 有什么好处?

javascript - 使用 Internet Explorer 时如何只加载一个特定的样式表?

javascript - 我的汽车上有旋转的轮子,但我希望它们以另一种方式旋转。我需要改变什么?

javascript - CSS3 边框半径到 HTML5 Canvas