Skip to content

Instantly share code, notes, and snippets.

@kartick14
Created December 5, 2018 06:53
Show Gist options
  • Save kartick14/f64ee656abfe2b4c18ce63c6efab5e3d to your computer and use it in GitHub Desktop.
Save kartick14/f64ee656abfe2b4c18ce63c6efab5e3d to your computer and use it in GitHub Desktop.
canvas drawing-erase-tools change with save as image to db
//https://jsfiddle.net/richardcwc/d2gxjdva/
<canvas id="canvas" width="500" height="500"></canvas>
<ul class="demoToolList">
<li>Brush color: <button class="brushcolor" type="button" value="black">Black</button><button class="brushcolor" type="button" value="white">White</button><button class="brushcolor" type="button" value="silver">Silver</button>
</li>
<li>Brush size: <button class="brushsize" type="button" value="small">Small</button><button class="brushsize" type="button" value="normal">Normal</button><button class="brushsize" type="button" value="large">Large</button></li>
<li><span style="display: block; margin-bottom: 20px;" class="line-opacity-controls">
<label for="line-opacity-control">Line opacity:</label>
<span class="info" id="rangeinfo" style="width: 15px; display: inline-block; text-align: center">50%</span>
<input type="range" min="1" max="100" value="50" step="1" id="line-opacity-control" style="margin-left: 20px; vertical-align: middle">
</span></li>
<li><button id="chooseEraserSimpleOutline" type="button" onclick="use_tool('erase');">Eraser</button></li>
</ul>
<div class="submit-section">
<label>Date: <?php echo date('d-m-Y'); ?></label>
<label>Name: <input type="text" name="creatorname" class="creatorname form-control" value="" /></label>
<input type="button" name="submitsketch" value="Submit" id="save-png">
</div>
<?php
function canvas_ajax_request() {
global $wpdb;
// The $_REQUEST contains all the data sent via ajax
if ( isset($_POST['action']) && $_POST['action'] == 'canvas_ajax_request' ) {
$canimgurl = $_POST['canimgurl'];
$creatorname = $_POST['creatorname'];
$curdate = date('d-m-Y');
// Now we'll return it to the javascript function
// Anything outputted will be returned in the response
echo $canimgurl;
$wpdb->insert(
'tz_canvas_table',
array(
'name' => $creatorname,
'canvasimg' => $canimgurl,
'date' => $curdate
),
array(
'%s',
'%s',
'%s'
)
);
}
//print_r($_POST);
// Always die in functions echoing ajax content
die();
}
add_action( 'wp_ajax_canvas_ajax_request', 'canvas_ajax_request' );
// If you wanted to also use the function for non-logged in users (in a theme for example)
add_action( 'wp_ajax_nopriv_canvas_ajax_request', 'canvas_ajax_request' ); ?>
<script type="text/javascript">
//Canvas
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
//Variables
/*var canvasx = jQuery(canvas).offset().left;
var canvasy = jQuery(canvas).offset().top;*/
var canvasx,canvasy;
var last_mousex = last_mousey = 0;
var mousex = mousey = 0;
var mousedown = false;
var tooltype = 'draw';
var brushcolor = '#000';
var brushsize = 2;
reOffset();
window.onscroll=function(e){ reOffset(); }
window.onresize=function(e){ reOffset(); }
document.getElementById('save-png').addEventListener('click', function () {
var dataURL = jQuery('#canvas').get(0).toDataURL();
var creatorname = jQuery('.creatorname').val();
jQuery.ajax({
url: '<?php echo admin_url( 'admin-ajax.php' ); ?>', // or example_ajax_obj.ajaxurl if using on frontend
data: {
'action': 'canvas_ajax_request',
'canimgurl' : dataURL,
'creatorname' : creatorname
},
type:"POST",
success:function(data) {
// This outputs the result of the ajax request
console.log(data);
location.reload();
},
error: function(errorThrown){
console.log(errorThrown);
}
});
});
var slider = document.getElementById("line-opacity-control");
var output = document.getElementById("rangeinfo");
output.innerHTML = slider.value; // Display the default slider value
// Update the current slider value (each time you drag the slider handle)
slider.oninput = function() {
output.innerHTML = this.value;
}
jQuery('.brushcolor').on('click', function(e) {
brushcolorcode = jQuery(this).val();
if(brushcolorcode == "white"){
brushcolor = '#fff';
}else if(brushcolorcode == "silver"){
brushcolor = '#C0C0C0';
}else if(brushcolorcode == "black"){
brushcolor = '#000';
}
use_tool('draw');
});
jQuery('.brushsize').on('click', function(e) {
brushsizecode = jQuery(this).val();
if(brushsizecode == "small"){
brushsize = 2;
}else if(brushsizecode == "normal"){
brushsize = 5;
}else if(brushsizecode == "large"){
brushsize = 10;
}
use_tool('draw');
});
//Mousedown
jQuery(canvas).on('mousedown', function(e) {
last_mousex = mousex = parseInt(e.clientX-canvasx);
last_mousey = mousey = parseInt(e.clientY-canvasy);
mousedown = true;
});
//Mouseup
jQuery(canvas).on('mouseup', function(e) {
mousedown = false;
});
//Mousemove
jQuery(canvas).on('mousemove', function(e) {
mousex = parseInt(e.clientX-canvasx);
mousey = parseInt(e.clientY-canvasy);
console.log(parseInt(slider.value) /100);
if(mousedown) {
ctx.beginPath();
if(tooltype=='draw') {
ctx.globalCompositeOperation = 'source-over';
ctx.strokeStyle = brushcolor;
ctx.lineWidth = brushsize;
ctx.globalAlpha = parseInt(slider.value) /100; // opacity at 0.5
} else {
ctx.globalCompositeOperation = 'destination-out';
ctx.lineWidth = brushsize;
}
ctx.moveTo(last_mousex,last_mousey);
ctx.lineTo(mousex,mousey);
ctx.lineJoin = ctx.lineCap = 'round';
ctx.stroke();
}
last_mousex = mousex;
last_mousey = mousey;
});
// Add touch event listeners to canvas element
canvas.addEventListener("touchstart", function(e)
{
// Mouse down location
last_mousex = mousex = (e.changedTouches ? e.changedTouches[0].clientX : e.clientX) - canvasx,
last_mousey = mousey = (e.changedTouches ? e.changedTouches[0].clientY : e.clientY) - canvasy;
mousedown = true;
}, false);
canvas.addEventListener("touchmove", function(e){
mousex = (e.changedTouches ? e.changedTouches[0].clientX : e.clientX) - canvasx,
mousey = (e.changedTouches ? e.changedTouches[0].clientY : e.clientY) - canvasy;
mousedown = true;
//console.log('mousex '+mousex); console.log('mousey '+mousey);
if(mousedown) {
ctx.beginPath();
if(tooltype=='draw') {
ctx.globalCompositeOperation = 'source-over';
ctx.strokeStyle = brushcolor;
ctx.lineWidth = brushsize;
ctx.globalAlpha = parseInt(slider.value) /100;// opacity at 0.5
} else {
ctx.globalCompositeOperation = 'destination-out';
ctx.lineWidth = brushsize;
}
ctx.moveTo(last_mousex,last_mousey);
ctx.lineTo(mousex,mousey);
ctx.lineJoin = ctx.lineCap = 'round';
ctx.stroke();
}
last_mousex = mousex;
last_mousey = mousey;
e.preventDefault()
}, false);
canvas.addEventListener("touchend", function(e){
mousedown = false;
}, false);
canvas.addEventListener("touchcancel", function(e){
mousedown = false;
}, false);
//Use draw|erase
use_tool = function(tool) {
tooltype = tool; //update
}
function reOffset(){
var BB=canvas.getBoundingClientRect();
canvasx=BB.left;
canvasy=BB.top;
}
</script>
@kartick14
Copy link
Author

Use it in http://tzuri.com/ site

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment