Display image based on button - javascript

How do I display the selected image only?
So what I wanted to happen is that I have set of buttons where the customer do customize the image.
E.g. User choose shapes as circle then displays, then there's next step where user will choose patter then displays inside the circle.
For the Shapes, i have the idea that the transparent part is only inside (applies to circle,rectangle and heart)
here's my code:
function display(){
if (document.getElementById('shape1').checked)
{
var ctx = document.getElementById('display_image').getContext('2d');
var imageObj = new Image();
imageObj.onload = function()
{ ctx.drawImage(imageObj, 0, 0); }
imageObj.src = 'http://image.flaticon.com/icons/png/512/33/33848.png';
}
if (document.getElementById('shape2').checked)
{
var ctx = document.getElementById('display_image').getContext('2d');
var imageObj = new Image();
imageObj.onload = function()
{ ctx.drawImage(imageObj, 0, 0); }
imageObj.src = 'http://image.flaticon.com/icons/png/512/33/33848.png';
}
}
if (document.getElementById('pattern1').checked)
{
var ctx = document.getElementById('display_image').getContext('2d');
var imageObj = new Image();
imageObj.onload = function()
{ ctx.drawImage(imageObj, 0, 0); }
imageObj.src = 'https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcTw_LgFWAcL6RzFH4EApgo69TX7xx6iUyPqLANgi5qdJ6QL9CY';
}
}
if (document.getElementById('pattern2').checked)
{
var ctx = document.getElementById('display_image').getContext('2d');
var imageObj = new Image();
imageObj.onload = function()
{ ctx.drawImage(imageObj, 0, 0); }
imageObj.src = 'https://s-media-cache-ak0.pinimg.com/originals/8b/09/59/8b0959d17298294904713dbb94b00827.png';
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form role="form" id="showchoices" name="showchoices" method="post">
<div> <input type="radio" id="shape1" name="shape_design" value="CIRCLE" onchange="display()"/> O
<input type="radio" id="shape2" name="shape_design" value="RECTANGLE" onchange="display()"/> [] </div>
<div> <input type="radio" id="pattern1" name="pat_design" value="pattern2" onchange="display()"/> pattern1
<input type="radio" id="pattern2" name="pat_design" value="pattern1" onchange="display()"/> pattern2 </div> -- i would like the pattern not to overlap the shape, send to back and visible.
</form>
<div id="display_image" name="display_image" width="400px" height="400px"> </div>
The idea is something like this but without the animation .
Radio button do triggers to display the images, just static display.
-- http://jsfiddle.net/djnBD/
and I'm combining this process to this sample too - https://jsfiddle.net/Twisty/955j8so3/27/
THANK YOU IN ADVANCE!!!

Here is a short example of how you could make what you want with HTML and jQuery. Hope it helps.
$(document).ready(function(){
$(document).on("click", "*[data-toggle='add-img']", function() {
var newImgSrc = $(this).attr("data-img");
var newImgId = $(this).attr("data-img-id");
var newImg = "<img src='"+newImgSrc+"' id='"+newImgId+"' />";
appendToContainer(newImg, newImgId);
});
$(document).on("click","*[data-toggle='remove-img']", function() {
var newImgId = $(this).attr("data-img-id");
if ($("#"+newImgId).length>0) $("#"+newImgId).remove();
});
function appendToContainer(img, imgId) {
var imgContainer = $("#images-container");
var zIndex = imgContainer.children("img").last().css("z-index");
var newZIndex = parseInt(zIndex)+1;
if ($("#imgId").length===0) imgContainer.append(img);
$("#imgId").css({"z-index":newZIndex});
}
});
#images-container > img {
position: absolute;
top: 40;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div>
img 1
img 2
img 3
delete img 1
delete img 2
delete img 3
</div>
<div id="images-container"></div>

i tried using canvas, got it right now:
function display(){
if (document.getElementById('shape1').checked)
{
var ctx = document.getElementById('display_image').getContext('2d');
var imageObj = new Image();
imageObj.onload = function()
{ ctx.drawImage(imageObj, 0, 0); }
imageObj.src = 'http://image.flaticon.com/icons/png/512/33/33848.png';
}
if (document.getElementById('shape2').checked)
{
var ctx = document.getElementById('display_image').getContext('2d');
var imageObj = new Image();
imageObj.onload = function()
{ ctx.drawImage(imageObj, 0, 0); }
imageObj.src = 'http://image.flaticon.com/icons/png/512/33/33848.png';
}
}
if (document.getElementById('pattern1').checked)
{
var ctx = document.getElementById('display_image').getContext('2d');
var imageObj = new Image();
imageObj.onload = function()
{ ctx.drawImage(imageObj, 0, 0); }
imageObj.src = 'https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcTw_LgFWAcL6RzFH4EApgo69TX7xx6iUyPqLANgi5qdJ6QL9CY';
}
}
if (document.getElementById('pattern2').checked)
{
var ctx = document.getElementById('display_image').getContext('2d');
var imageObj = new Image();
imageObj.onload = function()
{ ctx.drawImage(imageObj, 0, 0); }
imageObj.src = 'https://s-media-cache-ak0.pinimg.com/originals/8b/09/59/8b0959d17298294904713dbb94b00827.png';
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form role="form" id="showchoices" name="showchoices" method="post">
<div> <input type="radio" id="shape1" name="shape_design" value="CIRCLE" onchange="display()"/> O
<input type="radio" id="shape2" name="shape_design" value="RECTANGLE" onchange="display()"/> [] </div>
<div> <input type="radio" id="pattern1" name="pat_design" value="pattern2" onchange="display()"/> pattern1
<input type="radio" id="pattern2" name="pat_design" value="pattern1" onchange="display()"/> pattern2 </div> -- i would like the pattern not to overlap the shape, send to back and visible.
</form>
<canvas id="display_image" name="display_image" width="400px" height="400px"> </canvas>
It might won't work here but its already fine in my codes.

Related

How to draw images on an html canvas in a loop

I am trying to draw images on a canvas in a loop
In the following code, if I click on Next the 5 images appear one after the other. If I click on All only the last image appears
What is wrong?
<html>
<head>
<style>
.display-grid{
display: grid;
grid-template-columns: auto auto auto auto;
padding: 10px;
}
</style>
</head>
<body>
<div id="my-grid">
<div class="display-grid">
<span><canvas class="canvas" id="display-0"></canvas></span>
<span><canvas class="canvas" id="display-1"></canvas></span>
<span><canvas class="canvas" id="display-2"></canvas></span>
<span><canvas class="canvas" id="display-3"></canvas></span>
<span><canvas class="canvas" id="display-4"></canvas></span>
</div>
</div>
<button id="next-image">Next</button>
<button id="all-images">All</button>
<script type="text/javascript">
last_image = -1
var next_button= document.getElementById('next-image');
var all_button= document.getElementById('all-images');
next_button.onclick = function(){nextImage()};
all_button.onclick = function(){allImages()};
function nextImage() {
last_image ++
var canvas = document.getElementById('display-'+last_image.toString());
var context = canvas.getContext('2d');
var imageObj = new Image();
imageObj.onload = function() {
context.drawImage(imageObj, 0, 0);
};
imageObj.src = 'image_'+last_image.toString()+'.png';
}
function allImages() {
for (index = 0; index < 5; index++) {
var canvas = document.getElementById('display-'+index.toString());
var context = canvas.getContext('2d');
var imageObj = new Image();
imageObj.onload = function() {
context.drawImage(imageObj, 0, 0);
};
imageObj.src = 'image_'+index.toString()+'.png';
}
}
</script>
</body>
</html>
It happens because the onload function isn't called in the same order as the loop. Some images may take longer to load than others.
You could fix it by checking the image name to know which image is loaded, and then you know in which canvas it should be drawn.
function allImages() {
for (let index = 0; index < 5; index++) {
let imageObj = new Image();
imageObj.name = "display-"+index
imageObj.onload = function() {
console.log("loaded : " + this.name)
let canvas = document.getElementById(this.name);
let context = canvas.getContext('2d');
context.drawImage(this, 0, 0);
};
imageObj.src = 'image_'+index+'.png';
}
}

Trying to add a Filter to a Canvas Image

I'm Currently Trying to apply a filter or filters to a Canvas Image after its been uploaded to the page and but if they want to change filters to more blurry or to another filter it removes the image and you will have to re-upload the image. I plan on making it where there is a button to several different filters and then they click on the filter they want to apply to the image. Any Ideas on How to fix it?
Right now when you go to upload the image, it will blur it to 5px but if you want it less or more blurry for example it will remove the image.
Thank You! In advance! Heres a Live Link of my code:
https://jsfiddle.net/mbyvvszy/
html:
<canvas id="canvas" width="1000" height="500" class="playable-canvas"></canvas>
<div id="image_div">
<h1> Choose an Image to Upload </h1>
<input type='file' name='img' id='uploadimage' />
</div>
<div class="playable-buttons">
  <input id="edit" type="button" value="Edit" />
  <input id="reset" type="button" value="Reset" />
</div>
<textarea id="code" class="playable-code">
ctx.filter = 'blur(5px)';
</textarea>
Javascript :
var drawnImage;
function drawImage(ev) {
console.log(ev);
var ctx = document.getElementById('canvas').getContext('2d'),
img = new Image(),
f = document.getElementById("uploadimage").files[0],
url = window.URL || window.webkitURL,
src = url.createObjectURL(f);
img.src = src;
img.onload = function() {
drawnImage = img;
ctx.drawImage(img, 0, 0);
url.revokeObjectURL(src);
}
}
document.getElementById("uploadimage").addEventListener("change", drawImage, false);
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var textarea = document.getElementById('code');
var reset = document.getElementById('reset');
var edit = document.getElementById('edit');
var code = textarea.value;
function drawCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
eval(textarea.value);
}
reset.addEventListener('click', function() {
textarea.value = code;
drawCanvas();
});
edit.addEventListener('click', function() {
textarea.focus();
})
textarea.addEventListener('input', drawCanvas);
window.addEventListener('load', drawCanvas);
In drawCanvas, you clear the canvas but never re-draw the image. Just add a call to drawImage.
function drawCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
eval(textarea.value);
drawImage();
}

Save Canvas with selected background

I am working with canvas, right now I can save into DB and I can change the background image to one I choose of a image list.
My problem is when I tried to save the canvas with the background the saved image just show me the draw but doesn't the image background...can somebody help me with this?
Best Regards!
Here the code:
<script src="js/drawingboard.min.js"></script>
<script data-example="1">
var defaultBoard = new DrawingBoard.Board("default-board", {
background: "#ffff",
droppable: true,
webStorage: false,
enlargeYourContainer: true,
addToBoard: true,
stretchImg: false
});
defaultBoard.addControl("Download");
$(".drawing-form").on("submit", function(e) {
var img = defaultBoard.getImg();
var imgInput = (defaultBoard.blankCanvas == img) ? "" : img;
$(this).find("input[name=image]").val( imgInput );
defaultBoard.clearWebStorage();
});
$(function() {
$("#file-input").change(function(e) {
var file = e.target.files[0],
imageType = /image.*/;
if (!file.type.match(imageType))
return;
var reader = new FileReader();
reader.onload = fileOnload;
reader.readAsDataURL(file);
});
function fileOnload(e) {
var $img = $("<img>", { src: e.target.result });
var canvas = $("#default-board")[0];
var context = canvas.getContext("2d");
$img.load(function() {
context.drawImage(this, 0, 0);
});
}
});
</script>
<script src="js/yepnope.js"></script>
<script>
var iHasRangeInput = function() {
var inputElem = document.createElement("input"),
smile = ":)",
docElement = document.documentElement,
inputElemType = "range",
available;
inputElem.setAttribute("type", inputElemType);
available = inputElem.type !== "text";
inputElem.value = smile;
inputElem.style.cssText = "position:absolute;visibility:hidden;";
if ( /^range$/.test(inputElemType) && inputElem.style.WebkitAppearance !== undefined ) {
docElement.appendChild(inputElem);
defaultView = document.defaultView;
available = defaultView.getComputedStyle &&
defaultView.getComputedStyle(inputElem, null).WebkitAppearance !== "textfield" &&
(inputElem.offsetHeight !== 0);
docElement.removeChild(inputElem);
}
return !!available;
};
yepnope({
test : iHasRangeInput(),
nope : ["css/fd-slider.min.css", "js/fd-slider.min.js"],
callback: function(id, testResult) {
if("fdSlider" in window && typeof (fdSlider.onDomReady) != "undefined") {
try { fdSlider.onDomReady(); } catch(err) {}
}
}
});
// with this code I can change the background
$(document).ready(function () {
$("#cambiocanvas > input").click(function () {
var img = $(this).attr("src");
$(".drawing-board-canvas").css("background", "url(" + img + ")");
});
});
</script>
Here the form with the images:
<div class="tab-pane" id="derm">
<div class="row-fluid sortable">
<div class="box span3">
<section id="cambiocanvas">
<input id="yellowcanvas" class="canvasborder" type="image" src="http://2.imimg.com/data2/MB/BH/MY-651900/23-250x250.jpg">
<input id="bluecanvas" class="canvasborder" type="image" src="http://jsfiddle.net/img/logo.png">
<input id="greencanvas" class="canvasborder" type="image" src="https://www.gravatar.com/avatar/86364f16634c5ecbb25bea33dd9819da?s=128&d=identicon&r=PG&f=1">
</section>
</div>
<div class="box span9">
<div class="box-header well" data-original-title>
<h2><i class="icon-tasks"></i> </h2>
<div class="box-icon">
<i class="icon-chevron-up"></i>
<i class="icon-remove"></i>
</div>
</div>
<div class="box-content">
<div id="container">
<div class="example" data-example="1">
<div class="board" id="default-board"></div>
</div>
<form class="drawing-form" method="post" name="diagram" id="diagram" enctype="multipart/form-data">
<div id="board"></div>
<input type="hidden" name="image" value="">
<input type="hidden" name="id_user" value="<?php echo $id" />
<br><hr>
<button class="btn btn-info" id="btnUpload">Save</button>
</form>
<div id="ldiag" style="display:none;"><img src="images/loading4.gif" /></div>
<div class="progress1"></div>
<div id="diaga"></div>
</div>
</div>
</div>
CODE EDITED
Here the code:
<script src="js/drawingboard.min.js"></script>
<script data-example="1">
var defaultBoard = new DrawingBoard.Board("default-board", {
background: "#ffff",
droppable: true,
webStorage: false,
enlargeYourContainer: true,
addToBoard: true,
stretchImg: false
});
defaultBoard.addControl("Download");
$(".drawing-form").on("submit", function(e) {
var img = defaultBoard.getImg();
var imgInput = (defaultBoard.blankCanvas == img) ? "" : img;
$(this).find("input[name=image]").val( imgInput );
defaultBoard.clearWebStorage();
});
$(function() {
$("#file-input").change(function(e) {
var file = e.target.files[0],
imageType = /image.*/;
if (!file.type.match(imageType))
return;
var reader = new FileReader();
reader.onload = fileOnload;
reader.readAsDataURL(file);
});
function fileOnload(e) {
var canvas = $("#default-board")[0];
var context = canvas.getContext("2d");
var background = new Image;
background.src = canvas.style.background.replace(/url\(/|\)/gi,"").trim();
background.onload = function(){
var $img = $("<img>", { src: e.target.result });
$img.load(function() {
context.drawImage(backgroundImage, 0, 0, canvas.width, canvas.height);
context.drawImage(this, 0, 0);
});
}
}
});
The canvas element's background (image) is not part of the canvas content and thus not saved.
Solution if you can not redraw the canvas
If you want the background just render it onto the canvas before you save using the composite operation "destination-over" it will only add pixels where the canvas is transparent or semi transparent and you would see the Elements background.
ctx.globalCompositeOperation = "destination-over";
ctx.drawImage(backgroundImage,0,0);
ctx.globalCompositeOperation = "source-over"; // restore default
To load the canvas CSS background image
var background = new Image;
background.src = canvas.style.background.replace(/url\(/|\)/gi,"").trim();
// wait till it has loaded.
You may have to stretch the image
ctx.drawImage(background,0,0,ctx.canvas.width,ctx.canvas.height);
Alternative solution uses a offscreen canvas and draws background first then the original canvas.
// ensure that the image has loaded before running this code.
// canvas is the original canvas that you want to add the background to
// ctx is the origin canvas context
var can2 = document.createElement("canvas");
can2.width = canvas.width;
can2.height = canvas.height;
var ctx2 = can2.getContext("2d");
ctx2.drawImage(background,0,0,ctx.canvas.width,ctx.canvas.height);
ctx2.drawImage(canvas,0,0);
// put the new result back in the original canvas so you can save it without changing code.
ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height);
ctx.drawImage(can2,0,0);
OR to provide a copy and paste solution
function fileOnload(e) {
var canvas = $("#default-board")[0];
var context = canvas.getContext("2d");
var background = new Image;
background.src = canvas.style.background.replace(/url\(|\)/gi,"").trim();
background.onload = function(){
var $img = $("<img>", { src: e.target.result });
$img.load(function() {
context.drawImage(backgroundImage, 0, 0, canvas.width, canvas.height);
context.drawImage(this, 0, 0);
});
}
});
You almost done. Try change this code:
$(document).ready(function () {
$("#cambiocanvas > input").click(function () {
var img = $(this).attr("src");
$("#default-board").css("background", "url(" + img + ")");
});
});
To this one:
$(".canvasborder").click(function(){
var src = $(this).attr("src");
defaultBoard.setImg(src);
});
Like this:
var defaultBoard = new DrawingBoard.Board("default-board", {
background: "#fff",
droppable: true,
webStorage: false,
enlargeYourContainer: true,
addToBoard: true,
stretchImg: true
});
defaultBoard.addControl("Download");
$(".canvasborder").click(function(){
var src = $(this).attr("src");
defaultBoard.setImg(src);
});
$(".drawing-form").on("submit", function(e) {
var img = defaultBoard.getImg();
var imgInput = (defaultBoard.blankCanvas == img) ? "" : img;
$(this).find("input[name=image]").val( imgInput );
defaultBoard.clearWebStorage();
});
$(function() {
$("#file-input").change(function(e) {
var file = e.target.files[0],
imageType = /image.*/;
if (!file.type.match(imageType))
return;
var reader = new FileReader();
reader.onload = fileOnload;
reader.readAsDataURL(file);
});
function fileOnload(e) {
var canvas = $("#default-board")[0];
var context = canvas.getContext("2d");
var background = new Image;
background.src = canvas.style.background.replace(/url\(|\)/gi,"").trim();
background.onload = function(){
var $img = $("<img>", { src: e.target.result });
$img.load(function() {
context.drawImage(backgroundImage, 0, 0, canvas.width, canvas.height);
context.drawImage(this, 0, 0);
});
}
}
});
And will be work with any image you put in the select list, remember it has to be accompanied by an Access-Control-Allow-Origin header allowing the origin of your page (potentially via the * wildcard).

Html5 multiple canvas with image on one page

i have this php code
#for($i=1;$i<=$cate;$i++)
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12" style="min-height: 412px" id="etalon">
<canvas id="respondCanvas_{{$i}}" class="respondCanvas" style="position: absolute"></canvas>
<div class="col-md-2"><h3>
</h3></div>
</div>
</div>
<!-- /.row -->
#endfor
and this javascritp
var imageObj = new Image();
imageObj.src = "/frontEnd/images/coupons/back1.png";
for (var i=1;i<=2;i++) {
var canvas = document.getElementById("respondCanvas_"+i);
alert(i);
var context = canvas.getContext('2d');
imageObj.onload = function () {
context.drawImage(imageObj, 0, 0);
};
}
i want to create dynamic rows an each of them to have it's canvas.
Can anyone help me?
Thanks
I have managed to solve it ! Thanks anyway !
$(document).ready( function(){
var count = document.getElementsByClassName('respondCanvas').length;
var imageObj = new Image();
imageObj.src = "/frontEnd/images/coupons/back1.png";
var canvas = new Array();
var context = new Array();
for (var i=1;i<=count;i++) {
canvas[i] = document.getElementById("respondCanvas_"+i);
context[i] = canvas[i].getContext('2d');
}
imageObj.onload = function () {
for (var i=1;i<=count;i++) {
context[i].drawImage(imageObj, 0, 0);
}
};

How can I remove image from Fabric.js canvas using button

I'm very new to canvas and Fabric.js. I follow some tutorial and now can add image to canvas. but have no idea how to remove it. by clicking a button
HTML
<div id="container">
<input type="file" id="imageLoader" name="imageLoader" />
<input type="button" id="imageRemove" name="imageRemove" />
<canvas id="canvas" width="400" height="400" style="width:400px;height:400px" ></canvas>
JS
var canvas = new fabric.Canvas('canvas', {
backgroundColor: 'rgb(240,240,240)'
});
var imageLoader = document.getElementById('imageLoader');
imageLoader.addEventListener('change', handleImage, false);
function handleImage(e) {
var reader = new FileReader();
reader.onload = function (event) {
var img = new Image();
img.onload = function () {
var imgInstance = new fabric.Image(img, {
scaleX: 1,
scaleY: 1
})
canvas.add(imgInstance);
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
var imageRemove = document.getElementById('imageRemove');
imageLoader.addEventListener('change', handleRemove, false);
function handleRemove(e) {
canvas.remove(canvas.getActiveObject());
}
Edit:
Here is Jsfiddle
You can use clear() for clearing the canvas object and use renderAll() for redraw the given canvas.
Try This Code:
DEMO
HTML:
<div id="container">
<input type="file" id="imageLoader" name="imageLoader" />
Remove:<input type="button" value="remove" id="imageRemove" name="imageRemove" onClick="handleRemove()"/>
<canvas id="canvas" width="400" height="400" style="width:400px;height:400px" ></canvas>
JS Code:
var canvas = new fabric.Canvas('canvas', {
backgroundColor: 'rgb(240,240,240)'
});
var imageLoader = document.getElementById('imageLoader');
imageLoader.addEventListener('change', handleImage, false);
function handleImage(e) {
var reader = new FileReader();
reader.onload = function (event) {
var img = new Image();
img.onload = function () {
var imgInstance = new fabric.Image(img, {
scaleX: 1,
scaleY: 1
})
canvas.add(imgInstance);
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
//var imageRemove = document.getElementById('imageRemove');
//imageLoader.addEventListener('change', handleRemove, true);
function handleRemove() {
canvas.clear().renderAll(); // Here is your clear canvas function
}

Categories