Max*_* R. 5 html javascript canvas zooming
我想在我的 Web 应用程序中实现“缩放”功能,以按比例调整画布及其内容的大小(我不关心肮脏的质量)。
这是我的代码。每次我们想要缩放时,它都会重置画布以获取 Image 对象(用于使用drawImage方法),调整画布大小,然后使用drawImage方法按比例调整内容大小......
var Editor = {
// The following variables contains informations
// about the original canvas
data: ..., // imageData
width: 200,
height: 50,
// Zoom canvas
zoomCanvas: function(zoom){ // zoom in percents
var canvas = $('#canvas').get(0);
var context = canvas.getContext();
var data = this.data;
var scale = zoom / 100;
var width = this.width * scale;
var height = this.height * scale;
// Reset canvas to original size and imageData
this.resizeCanvas(this.width, this.height);
context.scale(1, 1);
context.putImageData(data, 0, 0);
// Get Image from original canvas data
var url = canvas.toDataURL();
var img = $('<img src="' + url + '">').get(0);
// Resize canvas, apply scale and draw Image with new proportions
this.resizeCanvas(width, height);
context.scale(scale, scale);
context.drawImage(img, 0, 0);
},
// Resize canvas
resizeCanvas: function(width, height){
// NOTE : I don't know exactly how to resize it so...
var canvas = $('#canvas').get(0);
canvas.width = width;
canvas.height = height;
$(canvas).width(width).attr('width', width);
$(canvas).height(height).attr('height', height);
var context = canvas.getContext('2d');
context.width = width;
context.height = height;
}
}
Run Code Online (Sandbox Code Playgroud)
它适用于 Zoom +,但不适用于 Zoom -。
不管怎样,我不认为这是实现我期望的最好方法,最好找到一种直接从 Editor.data 进行操作的方法,而不必每次都重置画布,或保存 Image 对象。另外,我不确定是否使用缩放方法......
任何帮助,将不胜感激
(对不起我的英语)
尝试利用<input type="range">,变换:scale(sx[, sy])
var canvas = document.querySelectorAll("canvas")[0]
, scale = document.getElementById("scale");
scale.addEventListener("change", function(e) {
canvas.style.transform = "scale("
+ e.target.value
+ ","
+ e.target.value
+ ")"
})Run Code Online (Sandbox Code Playgroud)
body {
height:800px;
}
canvas {
background:blue;
position:relative;
display:block;
}
#scale {
position:relative;
display:inline-block;
padding:8px;
}Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="scale" type="range" min="0" max="2" step="0.1" value=""/><br /><br /><br /><br /><br /><br /><br />
<canvas width="200" height="200"></canvas><br />Run Code Online (Sandbox Code Playgroud)