I'm a beginner at js.
using HTML5 canvas
Decorate the loaded image with some kind of decoration (draw text on the image with fillText, etc.) and
I would like to write it out in a format such as png per canvas.
However, the following error occurred and I cannot write it down well.I would appreciate it if you could let me know.
Script from origin' file:// 'has been blocked from loading by Cross-Origin Resource Sharing policy: Invalid response. Origin 'null' is there before not allowed access.
The source code is as follows:
<!DOCTYPE html>
<html lang="ja">
<head>
<metacharset="utf-8">
<title>Draw text on imported images</title>
<script src="myscript.js"crossorigin="anonymous"></script>
</head>
<body>
<h1>Draw text on imported images</h1>
<form>
<input type="button"value="draw in canvas" onclick="draw()">
</form>
<canvas id="mycanvas" width="400" height="400">
Use a Canvas-enabled browser.
</canvas>
<!--<form>
<input type="button"value="convert to image" onclick="chgImg()">
</form>-->
<div><img id="newImg">/div>
</body>
<script src="myscript.js"></script>
</html>
varcanvas= document.getElementById ('mycanvas');
varctx = canvas.getContext('2d');
function draw() {
varimg = new Image();
// Load local image
img.src = 'test.png';
img.onload=function(){
ctx.globalCompositeOperation='destination-over';
varpattern = ctx.createPattern(img, 'no-repeat');
ctx.fillStyle=pattern;
ctx.drawImage(img,10,10);
}
ctx.font='bold20px Verdana';
ctx.textAlign='left';
ctx.fillStyle='red';
ctx.fillText('test',20,200);
vardataURL=canvas.toDataURL();
document.getElementById("newImg").src=dataURL;
console.log(dataURL);
chgImg();
}
// Convert retrieved toDataURL() to png
function chgImg(){
varpng = canvas.toDataURL();
document.getElementById("newImg").src=png;
}
Regarding index.html, please try to correct the following two points.
It will now work.It will look like this:
<!DOCTYPE html>
<html lang="ja">
<head>
<metacharset="utf-8">
<title>Draw text on imported images</title>
</head>
<body>
<h1>Draw text on imported images</h1>
<form>
<input type="button"value="draw in canvas" onclick="draw()">
</form>
<canvas id="mycanvas" width="400" height="400">
Use a Canvas-enabled browser.
</canvas>
<!--<form>
<input type="button"value="convert to image" onclick="chgImg()">
</form>-->
<div><img id="newImg">/div>
<script src="myscript.js"></script>
</body>
</html>
By the way, if you open index.html from Chrome as Open File, please delete the crossorigin attribute of the script element.For this code, the test.png you are trying to open is read from the same domain, so you don't need to specify the crossorigin attribute in the first place.If you want to apply CORS using the crossdomain attribute, you must place it on some web server and load it with "http://" instead of "open the file."
© 2024 OneMinuteCode. All rights reserved.