问题描述
想要实现一个头像截图上传功能,在canvas上渲染一张图片,图片可放大缩小,再在canvas指定一个区域(红色框),
问题出现的环境背景及自己尝试过哪些方法
想要实现一个头像截图上传功能
相关代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
display: flex;
}
.left {
position: relative;
margin-right: 200px;
}
.box-border {
position: absolute;
width: 100px;
height: 100px;
left: 100px;
top: 100px;
border: 2px solid red;
}
</style>
</head>
<body>
<div class='box'>
<div class='left'>
<canvas id="canvas" style="display:block;border:1px solid #aaa;">
您的浏览器尚不支持canvas
</canvas>
<input type="range" id="scale-range" min="0.5" max="2.0" step="0.01" value="1.0"
style="display:block;margin:20px;" />
<div class='box-border'></div>
<p>canvas</p>
</div>
<div class='right'>
<img id='img' src="" alt="">
<p>截取得到后的图片</p>
</div>
</div>
<script>
var canvas = document.getElementById("canvas")
var context = canvas.getContext("2d")
var slider = document.getElementById("scale-range")
var image = new Image()
window.onload = function () {
canvas.width = 300
canvas.height = 500
var scale = slider.value
image.src = "img.jpg"
image.onload = function () {
drawImageByScale(scale)
slider.onmousemove = function () {
scale = slider.value
drawImageByScale(scale)
}
}
}
function drawImageByScale(scale) {
var imageWidth = 300 * scale
var imageHeight = 500 * scale
x = canvas.width / 2 - imageWidth / 2
y = canvas.height / 2 - imageHeight / 2
context.clearRect(0, 0, canvas.width, canvas.height) //第滑动一次input,range,清空canvas
context.drawImage(image, x, y, imageWidth, imageHeight)
getImg(canvas, context)
}
function getImg(canvas, context) {
context.drawImage(image, 0, 0, 100, 100);
var url = canvas.toDataURL("image/png")
document.getElementById('img').setAttribute('src', url)
}
</script>
</body>
</html>
你期待的结果是什么?实际看到的错误信息又是什么?
1.不管图片放大缩小,都只截取该区域,如图中红色区域
2.去掉canvas上截图多出来的图片(左上角绿色前头)
3.得出来的图片,只要红色框截取的部分,完整的图不要,其实就是绿色前头
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…