I'm trying to build a freeform lasso tool to clip an image inside canvas. I'm using fabric.js to draw the shape.
var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');
var img = document.createElement('IMG');
img.onload = function() {
var OwnCanv = new fabric.Canvas('c', {
isDrawingMode: true
});
OwnCanv.freeDrawingBrush.color = "purple"
OwnCanv.freeDrawingBrush.width = 4
ctx.clip();
ctx.drawImage(img, 0, 0);
}
img.src = "http://upload.wikimedia.org/wikipedia/commons/3/33/Jbassette4.jpg?uselang=fi";
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.4.0/fabric.min.js"></script>
<canvas id="c" width="500" height="500"></canvas>
This is my attempt which doesn't seem to work, what am I doing wrong here ?
Can anyone help me please? It would really be appreciated.
The image needs to be a fabric.Image.
You could try something like this:
var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');
var img = document.createElement('IMG');
img.onload = function() {
var OwnCanv = new fabric.Canvas('c', {
isDrawingMode: true
});
var imgInstance = new fabric.Image(img, {
left: 0,
top: 0,
});
OwnCanv.add(imgInstance);
OwnCanv.freeDrawingBrush.color = "purple"
OwnCanv.freeDrawingBrush.width = 4
OwnCanv.on('path:created', function(options) {
var path = options.path;
OwnCanv.isDrawingMode = false;
OwnCanv.remove(imgInstance);
OwnCanv.remove(path);
OwnCanv.clipTo = function(ctx) {
path.render(ctx);
};
OwnCanv.add(imgInstance);
});
}
img.src = "http://upload.wikimedia.org/wikipedia/commons/3/33/Jbassette4.jpg?uselang=fi";
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.4.0/fabric.min.js"></script>
<canvas id="c" width="500" height="500"></canvas>
See these resources for more:
http://fabricjs.com/fabric-intro-part-1/
Multiple clipping areas on Fabric.js canvas
Fabric.js Clip Canvas (or object group) To Polygon
Related
I need to draw an image with transparent background on canvas. I have a code that should do that:
var can = document.getElementById('canvasId');
var ctx = can.getContext('2d');
ctx.fillRect(50,50,500,500); // something in the background
var img = new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0);
}
img.src = "https://i.stack.imgur.com/7JXBD.png"; //transparent png
<canvas id="canvasId"></canvas>
But the background is not transparent:
Your code works perfectly - you just need an image with a transparent background - like this question mark:
var can = document.getElementById('canvasId');
var ctx = can.getContext('2d');
ctx.fillRect(50,50,500,500); // something in the background
var img = new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0);
}
img.src = "https://i.stack.imgur.com/RPEQQ.png"; //transparent png
<canvas id="canvasId"></canvas>
And to prove it's not just got a white background image, I set the background image of the body to red:
var can = document.getElementById('canvasId');
var ctx = can.getContext('2d');
ctx.fillRect(50,50,500,500); // something in the background
var img = new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0);
}
img.src = "https://i.stack.imgur.com/RPEQQ.png"; //transparent png
body {
background-color: red;
}
<canvas id="canvasId"></canvas>
The image that you are trying to display isn't transparent, it simply just has a transparent checkered background.
A link to an image which does have a transparent background can be found here
Using this link fixes your issue:
var can = document.getElementById('canvasId');
var ctx = can.getContext('2d');
ctx.fillRect(50, 50, 500, 500); // something in the background
var img = new Image();
img.src = "https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon#2.png?v=73d79a89bded"; //transparent png
img.onload = function() {
ctx.drawImage(img, 0, 0);
}
canvas {
border: 1px solid black;
}
<canvas id="canvasId" height="300" width="500"></canvas>
i'm currently trying to load a base64 img into my canvas
console.log('Change');
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var image = new Image();
image.onload = function() {
ctx.drawImage(image, 0, 0);
};
image.src = stack[1].save;
stack[1].save contains a valid base64 png img URL('data:image/png;base64,xxxxxx'), when i paste this URL into my browser i can see a valid img
The fact is that nothing changes and i dont have any error
If you could help me this will be awesome, thank's
Yes the code you have shared should work OK.
Here is an example
const canvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d')
var image = new Image();
image.onload = () => { ctx.drawImage(image, 0, 0) }
image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAQAAAAngNWGAAAAF0lEQVR42mNk+M9AFGAcVTiqcFQhCAAAf0sUAaSRMCEAAAAASUVORK5CYII="
var image2 = new Image()
image2.onload = () => { for(i=1; i<9; i++) ctx.drawImage(image2, 30*i, 5+4*i) }
image2.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO 9TXL0Y4OHwAAAABJRU5ErkJggg=="
<canvas id="canvas"></canvas>
The only thing that could be wrong is that stack[1].save that you are using...
I have a problem. I am creating simple game in Canvas using JavaScript. Image doesn't display after call clearRect(), does anyone know, how to solve it?
var left1 = 0;
var context1 = document.getElementById('canvas1').getContext('2d');
render1();
function render1() {
var image = new Image();
image.onload = function () {
context1.drawImage(image, left1, 0, 200, 200);
};
image.src = 'http://www.pngall.com/wp-content/uploads/2016/06/Earth-Free-Download-PNG.png';
left1++;
requestAnimationFrame(render1);
}
var left2 = 0;
var context2 = document.getElementById('canvas2').getContext('2d');
render2();
function render2() {
context2.clearRect(0, 0, 500, 250);
var image = new Image();
image.onload = function () {
context2.drawImage(image, left2, 0, 200, 200);
};
image.src = 'http://www.pngall.com/wp-content/uploads/2016/06/Earth-Free-Download-PNG.png';
left2++;
requestAnimationFrame(render2);
}
canvas {
display: block;
}
It works, but old images are not deleted:
<canvas id="canvas1" height="250" width="500"></canvas>
It doesn't work, because of clearRect():
<canvas id="canvas2" height="250" width="500"></canvas>
if you try to animate your image , its not necessary to make two canvas instead use a timer , i hope this will help
`
var left1 = 0;
var context1 = document.getElementById('canvas1').getContext('2d');
var canvas1 = document.getElementById('canvas1');
window.onload = init;
function init() {
setInterval(drawc, 1000 / 60);
};
function drawc() {
if (left1 > canvas1.width) {
left1 = 0;
}
render1();
}
function render1() {
with(context1) {
clearRect(0, 0, canvas1.width, canvas1.height);
var image = new Image();
image.src = 'http://www.pngall.com/wp-content/uploads/2016/06/Earth-Free-Download-PNG.png';
beginPath();
drawImage(image, left1, 0, 200, 200);
closePath();
fill();
left1++;
// requestAnimationFrame(render1);
}
};
For my website, I need to redraw an image from server which is continuously updating. I found the solution and tried but it still does not auto refresh. I also tried adding a dummy string to my image(local0.jpg) so that the browser does not use cached image but no success. What am I doing wrong?
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<canvas id="canvas" width="400" height="400"> </canvas>
<script>
var imageObj=new Image();
imageObj.src="local0.jpg?dummy=8484744"
imageObj.onload=function()
{
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
ctx.drawImage(imageObj,0, 0,canvas.width,canvas.height);
setTimeout(timedRefresh,1000);
}
function timedRefresh()
{
imageObj.src = "local0.jpg?dummy=8484749"
}
</script>
</body>
</html>
Try the following code
var imageObj = new Image();
imageObj.onload = function() {
drawOnCanvas();
setTimeout(timedRefresh, 1000);
}
// set src AFTER assigning load
imageObj.src = "local0.jpg?dummy=" + Math.random();
function timedRefresh() {
imageObj.src = "local0.jpg?dummy=" + Math.random();
//drawOnCanvas(); //flicker was due this line as it try to draw image load so i commented it... now it should work...
}
function drawOnCanvas() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(imageObj, 0, 0, canvas.width, canvas.height);
}
your function timedRefresh add random values to image
function timedRefresh()
{
imageObj.src = "local0.jpg?dummy=" + Math.floor((Math.random() * 10000) + 1);
}
I work at a web application for painting images. I use a CANVAS element and JavaScript to draw on it, but I have a problem: how can I load an image from the PC of the user and draw it on the canvas? I don't want to save it on the server, only on the webpage.
Here is a shortened version of the code:
HTML:
Open file: <input type="file" id="fileUpload" accept="image/*" /><br />
<canvas id="canvas" onmousemove="keepLine()" onmouseup="drawLine()" onmousedown="startLine()" width="900" height="600" style="background-color:#ffffff;cursor:default;">
Please open this website on a browser with javascript and html5 support.
</canvas>
JavaScript:
var x = 0;
var y = 0;
var clicked = false;
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
context.strokeStyle = "black";
context.lineCap = "round";
canvas.addEventListener('mousemove', function(e) { getMousePos(canvas, e); }, false);
takePicture.onchange = function (event) {
var files = event.target.files,
file;
if (files && files.length > 0) {
file = files[0];
processImage(file);
}
};
function processImage(file) {
var reader = new FileReader();
reader.readAsDataURL(file)
reader.onload = function(e) {
var img = new Image();
img.onload = function() {
context.drawImage(img, 100,100)
}
img.src = e.target.result;
}
}
// functions for drawing (works perfectly well)
function getMousePos(canvas, e) {
var rect = canvas.getBoundingClientRect();
x = evt.clientX - rect.left;
y = evt.clientY - rect.top;
}
function startLine() {
context.moveTo(x,y);
context.beginPath();
clicked = true;
}
function keepLine() {
if(clicked) {
context.lineTo(x,y);
context.stroke();
context.moveTo(x,y);
}
}
function drawLine() {
context.lineTo(x,y);
context.stroke();
clicked = false;
}
There's no copyright
const EL = (sel) => document.querySelector(sel);
const ctx = EL("#canvas").getContext("2d");
function readImage() {
if (!this.files || !this.files[0]) return;
const FR = new FileReader();
FR.addEventListener("load", (evt) => {
const img = new Image();
img.addEventListener("load", () => {
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.drawImage(img, 0, 0);
});
img.src = evt.target.result;
});
FR.readAsDataURL(this.files[0]);
}
EL("#fileUpload").addEventListener("change", readImage);
canvas {display: block;}
<input type='file' id="fileUpload" />
<canvas id="canvas" width="300" height="200"></canvas>
<html>
<head>
<script type="text/javascript" src="http://fiddle.jshell.net/js/lib/mootools-core-1.4.5-nocompat.js"></script>
<script type="text/javascript">
//<![CDATA[
window.addEvent('load', function() {
var imageLoader = document.getElementById('imageLoader');
imageLoader.addEventListener('change', handleImage, false);
var c = document.getElementById('myCanvas');
var ctx = c.getContext('2d');
function handleImage(e){
var reader = new FileReader();
reader.onload = function(event){
var img = new Image();
img.onload = function(){
c.width = img.width;
c.height = img.height;
ctx.drawImage(img,0,0);
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
});//]]>
</script>
</head>
<body>
<div style="background:#990; width:100%; padding:20px; ">
<label>Image File:</label><br/>
<input type="file" id="imageLoader" name="imageLoader"/>
</div>
<canvas id="myCanvas" ></canvas>
</body>
</html>
Here is a much simpler method, which doesn't use inefficient data urls:
var canvas = document.getElementById('canvas')
var input = document.getElementById('input')
var c2d = canvas.getContext('2d')
input.onchange=function() {
var img = new Image()
img.onload = function() {
canvas.width = this.width
canvas.height = this.height
c2d.drawImage(this, 0, 0)
URL.revokeObjectURL(this.src)
}
img.src = URL.createObjectURL(this.files[0])
}
<input type=file id=input> <br>
<canvas id=canvas></canvas>