const img = ref(null)
img.value = new Image()
img.value.src = base64
img.value.onload = () => {
if (img.value.complete) {
...加载成功
}
}
const mycanvas = ref(null)
const drawImage = () => {
const canvas = mycanvas.value
const ctx = canvas.getContext('2d')
ctx.clearRect(0,0,canvas.width,canvas.height)
ctx.save()
ctx.translate(originPoint.x, originPoint.y)
ctx.rotate(radian.value)
ctx.drawImage(img.value, -imageSize.width / 2, -imageSize.height / 2)
ctx.restore()
}
const radian = ref(0)
doRotate(angle) => {
radian.value = angle
drawImage()
}
doRotate(-(Math.PI / 180))
doRotate(Math.PI / 180)
doRotate(0)
const startRotation = (direction) => {
intervalId = setInterval(() => {
doRotate(direction)
},100)
}
startRotation(-(Math.PI / 180))
- 拖动画布
改变画布的原点
pc端事件mousedown or 移动端事件touchstart
<canvas id="mycanvas" ref="mycanvas" width="0" height="0" style="border:1px solid #d3d3d3;"
v-on:mousedown="onMouseDown" v-on:mouseup="onMouseUp" v-on:mousemove="onMouseMove"
v-on:touchstart="onTouchStart" v-on:touchend="onTouchEnd" v-on:touchmove="onTouchMove"></canvas>
var originPoint = {
x:0,y:0}
let startX
let startY
const onMouseDown = (e) => {
startX = e.clientX
startY = e.clientY
isMoveing = true
}
const onMouseMove = (e) => {
onMove(e.clientX, e.clientY)
}
const onMouseUp = () => {
isMoveing = false
mycanvas.value.style.cursor="auto"
}
const onTouchStart = (e) => {
startX = e.touches[0].clientX
startY = e.touches[0].clientY
isMoveing = true
}
const onTouchMove = throttle((e) => {
onMove(e.touches[0].clientX, e.touches[0].clientY)
}, 0)
const onTouchEnd = () => {
isMoveing = false
mycanvas.value.style.cursor="auto"
}
const onMove = (x, y) => {
if (!isMoveing) {
return
}
var dx = x - startX
var dy = y - startY
originPoint.x += dx
originPoint.y += dy
drawImage()
startX = x
startY = y
}
const canvas = mycanvas.value
var dataURL = canvas.toDataURL()
var file = dataURLtoFile(dataURL)
function dataURLtoFile(dataurl) {
let arr = dataurl.split(',')
let mime = arr[0].match(/:(.*?);/)[1]
let bstr = atob(arr[1])
let n = bstr.length
let u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
return new File([u8arr], 'image.png', {
type: mime })
}
const onScale = (rate) => {
scale.value = scale.value + rate
drawImage()
}
onScale(0.15)
const onRecover = () => {
scale.value = 1
radian.value = 0
originPoint = {
x: imageSize.width / 2,y: imageSize.height / 2}
drawImage()
}