html5 canvas javascript copy picture - javascript

I have a html5 page. It uses JQuery and sketch.js (for free drawing). I am NOT going to connect it to any web server. At this moment, I would like to be use this javascript as desktop application. My purpose is to copy image from one canvas to the other canvas in the same page. After draw something by free hand, I could see url is copied to textarea, but no picture after clicking Show URL link. Could someone give me hints how to make an copy of image from one canvas to the other?
/1/ Source codes, one need to add html tag in the beginning, do not forget <>
<head>
<title>sketch and free hand drawing</title>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js">
</script>
<![endif]-->
<meta charset="UTF-8">
<meta http-equiv="Content-Type" content="image/png"/>
<script src="js/jquery-1.11.0.min.js"></script>
<script src="js/sketch.js"></script>
/2/One need to add /head above. do not forget <>
<body>
<script>
function toDo(){
console.log(document.getElementById("colors_sketch").toDataURL("image/png"));
document.getElementById("cvs").value=document.getElementById("colors_sketch").toDataURL("image/png");
document.getElementById("txt").value=document.getElementById("colors_sketch").toDataURL("image/png");
}
</script>
<div class="tools">
Download
</div>
<div class="tools">
show URL
</div>
<textarea id="txt"></textarea>
<hr/>
<canvas id="colors_sketch" width="800" height="300">hello</canvas>
<hr/>
<canvas id="cvs" width="800" height="300"></canvas>
<script type="text/javascript">
$(function() {
$.each(['#f00', '#ff0', '#0f0', '#0ff', '#00f', '#f0f', '#000', '#fff'], function() {
$('#colors_demo .tools').append("<a href='#colors_sketch' data-color='" + this + "' style='width: 10px; background: " + this + ";'></a> ");
});
$.each([3, 5, 10, 15], function() {
$('#colors_demo .tools').append("<a href='#colors_sketch' data-size='" + this + "' style='background: #ccc'>" + this + "</a> ");
});
$('#colors_sketch').sketch();
});
/3/ one need to add /script above and /body above and /html above do not forget <>

To move an image from one canvas to another, you can simply use drawImage
destinationContext.drawImage(sourceCanvas,0,0);
The pixels from the source canvas will be drawn onto the destination canvas.
A Demo: http://jsfiddle.net/m1erickson/2hb56/
I tried modifying your code, but it appears you also have a design issue.
SketchJS will erase your copied image in preparation for it's own drawings (the copied image is erased).
Example code copying pixels from one canvas to another:
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script src="http://code.jquery.com/jquery.min.js"></script>
<script src="sketch.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
// get references to canvases and contextx
sourceCanvas=document.getElementById("source");
sourceContext=sourceCanvas.getContext("2d");
destinationCanvas=document.getElementById("destination");
destinationContext=destinationCanvas.getContext("2d");
// draw a test image into the source canvas
var testImg=new Image();
testImg.onload=function(){
sourceContext.drawImage(testImg,0,0);
}
testImg.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house-icon.png";
// when the button is clicked
// copy the source canvas onto the destination canvas
$("#copy").click(function(){
destinationContext.drawImage(sourceCanvas,0,0);
})
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="source" width=256 height=256></canvas><br>
<button id="copy">Copy canvas above to canvas below</button><br>
<canvas id="destination" width=256 height=256></canvas>
</body>
</html>

Related

I was not able to see images while converting html page to pdf using javascript

here is my code while i download pdf images attributes of html are missing.
suppose in cases like generating invoices we should print tables containing details along with logo.
but images are not displaying in downloaded pdf using this code.Provide me with possible resolution and reason for this.thanks in advance
$(document).on('click', '#btn', function() {
let pdf = new jsPDF();
let section = $('body');
let page = function() {
pdf.save('pagename.pdf');
};
pdf.addHTML(section, page);
})
html,
body {
overflow-x: hidden;
}
#btn {
padding: 10px;
border: 0px;
margin: 50px;
cursor: pointer;
}
<!DOCTYPE html>
<html>
<head>
<title>HTML with Image</title>
<META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW">
<style type="text/css">
</style>
</head>
<body>
<button id="btn">Convert to PDF</button>
<div id="text">
<h2>HTML Page with Image to PDF</h2>
<img src="http://photojournal.jpl.nasa.gov/jpeg/PIA17555.jpg" width="300px">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.0.272/jspdf.debug.js"></script>
<script src="custom.js"></script>
<script type="text/javascript">
</script>
</body>
</html>
all the html elements are working fine except images . kindly help me with resolving this.
jsPdf does not support adding images the way you are trying to add them, because addtHtml function uses the html2canvas module, to convert your Html to canvas, so jsPdf can render it into pdf. Please check this link below.
https://weihui-guo.medium.com/save-html-page-and-online-images-as-a-pdf-attachment-with-one-click-from-client-side-21d65656e764

Trying to change background color with variable

Trying to change color using a variable, console works but color not changing when I click on the square.
Color is the variable I want to use.
I have tried an actual string value and that does not work.
<!DOCTYPE html>
<html>
<head>
<link href="main.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<h1>Test Your Reactions!</h1>
<p>Click on the shapes as fast as you can</p>
<div id="shapes">
</div>
<script>
function myFunction() {
var colour = '#'+((Math.random() * (1<<24)|0).toString(16).slice(-6));
document.getElementById("shapes").style.backgroundColour = colour;
console.log(colour);
}
</script>
</body>
</html>
its backgroundColor not Colour .. you have an extra u
You need to replace backgroundColour by backgroundColor without u :
document.getElementById("shapes").style.backgroundColour = colour;
______________________________________________________^
Must be :
document.getElementById("shapes").style.backgroundColor = colour;
NOTE 1: You need to trigger the function to see the effect and you must also give your target div shapes a width/height so you can see it.
NOTE 2: You must listen on DOMContentLoaded event to make sure all the elements are loaded to the DOM before calling your script.
Working sample:
<!DOCTYPE html>
<html>
<head>
<link href="main.css" rel="stylesheet" type="text/css" />
<style>
#shapes {
width: 100px;
height: 100px;
border: 1px solid #000;
}
</style>
</head>
<body>
<h1>Test Your Reactions!</h1>
<p>Click on the shapes as fast as you can</p>
<div id="shapes">
</div>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var shapes = document.getElementById("shapes");
shapes.addEventListener('click', myFunction, false);
});
function myFunction() {
shapes.style.backgroundColor = "#" + (Math.random() * (1 << 24) | 0).toString(16).slice(-6);
}
</script>
</body>
</html>
Try this
const shapes = document.getElementById("shapes"); // You declare once, then you can reuse
function myFunction() {
var colour = '#'+((Math.random() *(1<<24)|0).toString(16).slice(-6));
shapes.style.backgroundColor = colour;
console.log(colour);
}
shapes.addEventListener('click', myFunction); // I guess you want to click somewhere
<h1>Test Your Reactions!</h1>
<p>Click on the shapes as fast as you can</p>
<div id="shapes">Shapes</div>
Below code gives the expected result. please take it.
<!DOCTYPE html>
<html>
<head>
<link href="main.css" rel="stylesheet" type="text/css"/>
<style>
#shapes {
width: 300px;
height: 300px;
background-color: coral;
color: white;
}
</style>
</head>
<body>
<h1>Test Your Reactions!</h1>
<p>Click on the shapes as fast as you can</p>
<div id="shapes" onClick="myFunction();">
test
</div>
<script>
function myFunction() {
var colour = '#'+((Math.random() * (1<<24)|0).toString(16).slice(-6));
document.getElementById("shapes").style.backgroundColor = colour;
console.log(colour);
}
</script>
</body>
</html>

paper.js vector slow performance

I've been trying to get this fairly simple program to work and am running into performance problems.
I'm trying to make thousands of tiny colored dots on a canvas. Creating so many new paths is slowing down my computer before I am able to get the amount that I want on the canvas, and then crashes when I try to export the canvas as an SVG. I looked into using symbols, but I need the colors of each dot to be different.
The goal is for every color and position to be completely random and unique, and to have the dots completely cover the canvas. The canvas will eventually need to be printed 55 inches by 75 inches, so I will want the circles to be of high enough resolution that they don't look pixellated when printed. This can mean either being able to export to a high enough raster resolution or to export to a vector.
I'm using paper.js because I figured that it would be best to render the dots as vector graphics so that I can print them at high quality when I need to, but is there a better way to do this?
Thanks.
the html below is everything (except for the paper.js library).
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="css/style.css">
<!-- Load the Paper.js library -->
<script type="text/javascript" src="js/paper.js"></script>
<!-- Define inlined PaperScript associate it with myCanvas -->
<style type="text/css">
html,
body {
margin: 0;
overflow: hidden;
height: 100%;
}
/* Scale canvas with resize attribute to full size */
canvas[resize] {
width: 550px;
height: 750px;
background-color: #39ff14;
}
</style>
<script type="text/paperscript" canvas="myCanvas">
paper.install(window);
tool.fixedDistance = .1;
var layer = project.activeLayer;
function onMouseMove(event) {
var radius = (1 * Math.random()) + .5;;
var path = new Path.Circle({
center: Point.random() * view.size,
radius: radius,
fillColor: "#000000".replace(/0/g,function(){return (~~(Math.random()*16)).toString(16);}),
})
}
// START DOWNLOAD BUTTON &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
function downloadDataUri(options) {
if (!options.url)
options.url = "http://download-data-uri.appspot.com/";
$('<form method="post" action="' + options.url
+ '" style="display:none"><input type="hidden" name="filename" value="'
+ options.filename + '"/><input type="hidden" name="data" value="'
+ options.data + '"/></form>').appendTo('body').submit().remove();
}
$('#export-button').click(function() {
var svg = project.exportSVG({ asString: true });
downloadDataUri({
data: 'data:image/svg+xml;base64,' + btoa(svg),
filename: 'export.svg'
});
});
// END DOWNLOAD BUTTON &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
</script>
</head>
<body>
<canvas id="myCanvas" resize></canvas>
<input type="button" value="Download as SVG" id="export-button">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<!-- <script src="js/scripts.js"></script> -->
</body>
</html>

How to export Jchartfx svg chart to canvas

I tried to export jchartfx to canvas using html2canvas.js but it only converts other attributes into canvas but svg element is displayed as blank area. here is my code.
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Using an existing canvas to draw on</title>
<style>
canvas {
border: 1px solid black;
}
button {
clear: both;
display: block;
}
#content {
background: rgba(100, 255, 255, 0.5);
padding: 50px 10px;
}
</style>
<link rel="stylesheet" type="text/css" href="css/jchartfx.attributes.css" />
<link rel="stylesheet" type="text/css" href="css/jchartfx.palette.css" />
<script type="text/javascript" src="./js/jchartfx/jchartfx.system.js"></script>
<script type="text/javascript" src="./js/jchartfx/jchartfx.coreVector.js"></script>
<script type="text/javascript" src="./js/jchartfx/jchartfx.advanced.js"></script>
<script type="text/javascript" src="./js/jquery.min.js"></script>
<script type="text/javascript" src="./js/exportLibrary.js"></script>
<style>
.exportChart{}
.exportTable{max-width:700px;border:1px solid blue; margin:2px;}
</style>
<script type="text/javascript" >
var chart1;
function loadChart(){
chart1 = new cfx.Chart();
chart1.setGallery(cfx.Gallery.Pie);
var title;
title = new cfx.TitleDockable();
title.setText("Sample Demo");
chart1.getTitles().add(title);
var divHolder = document.getElementById('ChartDiv1');
PopulateCarProduction(chart1);
chart1.create(divHolder);
}
function PopulateCarProduction(chart) {
var items = [{
"Proportion": 70,
"Month": "Jan"
}, {
"Proportion": 30,
"Month": "Feb"
}];
chart.setDataSource(items);
}
</script>
</head>
<body onload="loadChart()">
<div><h1>HTML content to render:</h1>
<div id="content">
<div class="exportChart" id="ChartDiv1" style="width:600px;height:400px"></div>
<div class="exportTable" id="TableDiv1" style="width:600px;">
<table id="table1" >
<tr><th style="color:#f0f">1Column one</th><th>Column Two</th><th>Column one</th><th>Column Two</th><th>Column Two</th></tr>
<tr><td>Data11</td><td>Data12</td><td>Data11</td><td>Data12</td><td>Data12</td></tr>
<tr><td> Data21</td><td>Data22 </td><td> Data21</td><td>Data22 </td><td>Data22 </td></tr>
<tr><td> Data31</td><td>Data32 </td><td> Data31</td><td>Data32 </td><td>Data32 </td></tr>
</table>
</div>
</div>
</div>
<h1>Existing canvas:</h1>
<canvas width="1000" height="800"></canvas>
<script type="text/javascript" src="tableexport/html2canvas.js"></script>
<button>Run html2canvas</button>
<script type="text/javascript">
var canvas = document.querySelector("canvas");
var ctx = canvas.getContext("2d");
document.querySelector("button").addEventListener("click", function() {
html2canvas(document.querySelector("#content"), {canvas: canvas}).then(function(canvas) {
console.log('Drew on the existing canvas');
});
}, false);
</script>
</body>
</html>
The table is converted into canvas but svg is not converted. i need to convert svg to canvas with styles.
Here is the generated output.
It's due to security constraints. If a SVG contains any external references (foreignObject such as image data, css etc.) the browser will not allow the SVG to be drawn.
For security purposes, Gecko places some restrictions on SVG content
when it's being used as an image:
External resources (e.g. images, stylesheets) cannot be loaded, though they can be used if inlined through BlobBuilder [Blob] object URLs or
data: URIs.
[...]
Note that the above restrictions are specific to image contexts; they
don't apply when SVG content is viewed directly, or when it's embedded
as a document via the <iframe>, <object>, or <embed> elements.
Source
You could always save the SVG itself as an image, or if an absolute requirement, parse it using for example a library such as canvg.

Troubles applying CSS to a SVG

this is my first time here. I load a SVG with Javascript into an HTML document. I need to replace the color of this SVG (it's a black image with transparency), which is placed into a canvas; however, when I put the css (style), nothing happens.
This is my code:
<!DOCTYPE html>
<html>
<head>
<title>TEST CANVAS</title>
<script>
function draw_img(){
var img = document.getElementById("test");
test.width = 300;
test.height = 300;
var ctx = test.getContext('2d');
var source = new Image();
source.src = './field/image.svg';
source.onload = function(){
ctx.drawImage(source, 0, 0);
}
}
</script>
</head>
<style>
canvas#test {
fill:darkred;
}
</style>
<body onload = "draw_img();">
<h1>TEST</h1>
<canvas id="test"></canvas>
</body>
</html>
What's wrong with it? Sorry for my bad English and thanks in advance
Canvasses are bitmap images. You can't apply CSS styles to them and expect that to change their colour. Once the SVG is rendered into the Canvas, it's contents are fixed, and can't be changed (except by pixel manipulation).
If you want to manipulate the colours of your SVG, you should inline it.
<style>
svg#test {
fill:darkred;
}
</style>
<body>
<h1>TEST</h1>
<svg id="test">
<rect width="50" height="50"/>
</svg>
</body>
Demo here

Categories

Resources