HTML
<canvas id="canvas">您的机型版本不支持canvas</canvas>
2、初始化画布
function __init() {
var canvas = document.getElementById('canvas');
var oGC = canvas.getContext('2d');
var header_h = api.pageParam.h;
var w = api.winWidth;
var h = api.winHeight;
canvas.width = w - 60;
canvas.height = h - 80;
var strokeColor = "blue";
var isMouseDown = false;//是否按下鼠标
var lastLoc = { x: 0, y: 0 };//上一次鼠标的坐标点
canvas.addEventListener('touchstart', function (ev) {
ev.preventDefault()
isMouseDown = true;
lastLoc = windowToCanvas(ev.touches[0].clientX, ev.touches[0].clientY);
})
canvas.addEventListener('touchmove', function (ev) {
ev.preventDefault()
var curLoc = windowToCanvas(ev.touches[0].clientX, ev.touches[0].clientY);
oGC.beginPath();
oGC.moveTo(lastLoc.x, lastLoc.y);
oGC.lineTo(curLoc.x, curLoc.y);
oGC.strokeStyle = '#000';
oGC.lineWidth = 6;
oGC.lineCap = "round";
oGC.lineJoin = "round";
oGC.stroke();
lastLoc = curLoc;
})
canvas.addEventListener('touchend', function (ev) {
ev.preventDefault()
isMouseDown = false;
})
}
2-1、拿到当前点击的坐标点
function windowToCanvas(x, y) {
// 拿到canvas距离文档里offsetLeft 和 offsetTop
var clientRect = canvas.getBoundingClientRect();
return {
x: Math.round(x - clientRect.left),
y: Math.round(y - clientRect.top)
}
}
2-2、清空画布
function reset() {
var canvas = document.getElementById('canvas');
var oGC = canvas.getContext('2d');
var header_h = api.pageParam.h;
var w = api.winWidth;
var h = api.winHeight;
oGC.clearRect(0, 0, w - 60, h - 80);
}
3、处理画布,回调图片
function rotateBase64(data,cb) {
var imgView = new Image();
imgView.src = data;
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
var cutCoor = { sx: 0, sy: 0, ex: 0, ey: 0 }; // 裁剪坐标
imgView.onload = function() {
var imgW = imgView.width;
var imgH = imgView.height;
var size = imgH;
canvas.width = size * 2;
canvas.height = size * 2;
cutCoor.sx = size;
cutCoor.sy = size - imgW;
cutCoor.ex = size + imgH;
cutCoor.ey = size + imgW;
context.translate(size, size);
context.rotate(Math.PI / 2 * 3);
context.drawImage(imgView, 0, 0);
const imgData = context.getImageData(cutCoor.sx, cutCoor.sy, cutCoor.ex, cutCoor.ey);
canvas.width = imgH;
canvas.height = imgW;
context.putImageData(imgData, 0, 0);
cb && cb(canvas.toDataURL('image/png'))
};
}
4、确认提交
function submit() {
var canvas = document.getElementById('canvas');
var oGC = canvas.getContext('2d');
var strDataURI = canvas.toDataURL();
rotateBase64(strDataURI,function(img){
console.log(img)
})
}