#verticalFlip
每次单击元素时,您都在重复完全相同的一系列操作:
- 选择画布元素
- 获取对其上下文的引用
- 创建新图像并将事件侦听器添加到其加载事件
- 通过设置源来加载图像
- 加载图像时在画布上绘制图像的“翻转”版本
由于每次单击文档时都在加载然后翻转图像,因此永远不会有任何跟踪的“状态”来确定方向。您的方法存在一些问题,请允许我提供重构的解决方案:
// jQuery document ready function
$(function() {
// Cache jQuery selections
var $verticalFlip = $("#verticalFlip");
// Cache canvas element and context
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
// Cache the image object
var image = new Image();
// Create loaded and flipped states for the image
var imageFlipped = false;
var imageLoaded = false;
// Add event handlers
$verticalFlip.on("click", onVerticalFlipClick);
image.onload = onImageLoad;
// Load image function
function loadImage(src) {
imageLoaded = false;
image.src = src;
};
// Draw image function
function drawImage(flip) {
// Only draw the image on the canvas if it has loaded
if (imageLoaded) {
// Set the scale and translate the context based on the passed flip boolean
context.save();
context.scale(1, flip ? -1 : 1);
context.translate(0, flip ? -image.height : 0);
context.drawImage(image, 0, 0);
context.restore();
}
};
// Image load callback
function onImageLoad(event) {
imageLoaded = true;
canvas.width = image.width;
canvas.height = image.height;
drawImage(imageFlipped);
};
// Click callback
function onVerticalFlipClick(event) {
// Invert the flip state
imageFlipped = !imageFlipped;
// Draw the image on the canvas
drawImage(imageFlipped);
};
// Finally, load the image
loadImage("http://myurl.com/" + user_id + "_temp.jpg");
});