캔버스 요소에 배치 된 크리스마스 트리 이미지로 응용 프로그램을 만듭니다. 드래그 이미지 위에 이미지가있을 수 있습니다. 트리가 드래그 가능한 이미지로 장식 된 후에는 사용자가 전체 컴포지션 (캔버스 + 이미지)을 PNG 파일로 저장할 수 있어야합니다. 문제는 이미지를 캔버스로 끌면 크리스마스 트리 뒤에 숨어 있다는 것입니다. 고칠 수있게 도와 주시겠습니까?이미지를 캔버스 위로 드래그하여 PNG로 저장
<html>
<head>
<script>
\t
\t \t function allowDrop(e)
{
e.preventDefault();
}
function drag(e)
{
//store the position of the mouse relativly to the image position
e.dataTransfer.setData("mouse_position_x",e.clientX - e.target.offsetLeft);
e.dataTransfer.setData("mouse_position_y",e.clientY - e.target.offsetTop );
e.dataTransfer.setData("image_id",e.target.id);
}
function drop(e)
{
e.preventDefault();
var image = document.getElementById(e.dataTransfer.getData("image_id"));
var mouse_position_x = e.dataTransfer.getData("mouse_position_x");
var mouse_position_y = e.dataTransfer.getData("mouse_position_y");
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
\t \t \t var imageObj=new Image();
imageObj.onload=function(){
ctx.save();
\t \t \t ctx.drawImage(this,0,0,canvas.width,canvas.height);
ctx.restore();
\t \t }
\t \t
\t \t imageObj.src="bg.png";
// the image is drawn on the canvas at the position of the mouse when we lifted the mouse button
ctx.drawImage(image , e.clientX - canvas.offsetLeft - mouse_position_x , e.clientY - canvas.offsetTop - mouse_position_y);
}
function convertCanvasToImage() {
var canvas = document.getElementById('canvas');
\t
var image_src = canvas.toDataURL("image/png");
window.open(image_src);
\t
}
\t \t
\t \t
</script>
\t <style type="text/css">
\t body {
\t text-align: center;
}
#wrapper {
\t text-align: left;
\t width: 870px;
\t height:566px;
\t margin-left: auto;
\t margin-right: auto;
}
#options{
\t width: 70px;
\t height:566px;
\t float:left;
}
#options img {
\t margin-bottom: 15px;
}
#canvas{
\t width:800px;
\t height:566px;
\t float:left;
\t background-image:url(../images/bg.png);
}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<div id="options">
<img id="img1" draggable="true" ondragstart="drag(event)" src='estrela.png'>
<img id="img2" draggable="true" ondragstart="drag(event)" src='bola.png'>
<img id="img3" draggable="true" ondragstart="drag(event)" src='sino.png'>
<img id="img4" draggable="true" ondragstart="drag(event)" src='bota.png'>
<img id="img5" draggable="true" ondragstart="drag(event)" src='anjo.png'>
<img id="img6" draggable="true" ondragstart="drag(event)" src='laco.png'>
</div>
<canvas id="canvas" onDrop="drop(event)" onDragOver="allowDrop(event)" width="800" height="566"></canvas>
<input type="button" onClick="convertCanvasToImage()" value="Gerar Imagem" style="float:right"/>
</body>
감사 :
여기에 코드입니다!
아마 모든 img 요소 앞에 canvas 요소를 배치해야할까요? – markE
이미 시도했는데 ... 작동하지 않습니다. ( –